<template>
    <div class="tu">
        <div id="textimg">
            <CaptureItem>
                <template #image>
                    <img :src="img" alt="上传图片">
                </template>
                <template #opration="opretionObj">
                    <button @click="save(opretionObj)">保存</button>
                </template>
            </CaptureItem>
        </div>
        <input type="file" name="file" @input="onFileInput">
    </div>
</template>

<script setup lang="ts">
import CaptureItem from "./CaptureItem.vue";
import { ref, reactive } from "vue"
/**
 * 1.上传图片并展示
 * 2.截取图片
 * 3.获取截取后图片
 * 4.返回截图后图片
 */
let img = ref(undefined);
const onFileInput = (e: Event) => {
    let file = e as any
    file = file.target.files[0]
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e: any) {
        img.value = e.target.result
    }
}

const save = (obj: any) => {
    obj = obj.data
    let can = document.createElement("canvas")
    can.width = obj.captureWidth
    can.height = obj.captureHeight
    let ctx = can.getContext('2d')
    if (img.value) {
        let image = new Image()
        image.src = img.value
        image.onload = function () {
            ctx?.drawImage(image, obj.captureLeft, obj.captureTop, obj.captureWidth, obj.captureHeight, 0, 0, obj.captureWidth, obj.captureHeight)
            console.log(can.toDataURL());
        }
    }
}
</script>

<style scoped>
.tu {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-content: center;
}

#textimg {
    min-height: 50px;
    width: auto;
    margin: 0 auto;
}

img {
    position: absolute;
    left: 0;
    top: 0;
}

button {
    position: absolute;
    bottom: -30px;
    z-index: 1000;
}
</style>
